package com.example.mycarcalling.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.example.lib_cache.service.ApiService;
import com.example.lib_cache.viewmodel.LoginActivityViewModel;
import com.example.lib_cache.viewmodel.RoutePlanActivityViewModel;
import com.example.lib_common.util.DrivingRouteOverlay;
import com.example.mycarcalling.R;
import com.example.mycarcalling.databinding.ActivityRoutePlanBinding;

import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class RoutePlanActivity extends AppCompatActivity {

    @Inject
    ApiService apiService;

    private Context mContext;

    private ActivityRoutePlanBinding activityRoutePlanBinding;
    private RoutePlanActivityViewModel routePlanActivityViewModel;

    public final static String TAG = RoutePlanActivity.class.getSimpleName();

    private BaiduMap baiduMap = null;
    ProgressDialog progressDialog = null;

    private RoutePlanSearch mSearch;
    private OnGetRoutePlanResultListener listener;

    private PassengerDialog passengerDialog = null;

    private BitmapDescriptor mBitmapDescriptor =
            BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding);




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        activityRoutePlanBinding = DataBindingUtil.setContentView(this,
                R.layout.activity_route_plan);

//        setContentView(R.layout.activity_route_plan);
        init();
    }

    private void init(){
        initView();
        initData();
        initListener();
        initObserve();

        //绘制路线
        startRoutePlan();
    }

    private void initObserve(){

        routePlanActivityViewModel.getApiResult().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                progressDialog = new ProgressDialog(mContext);
                progressDialog.setIcon(R.mipmap.ic_launcher);
                progressDialog.setTitle("订单");
                progressDialog.setMessage("发送中...");
                progressDialog.setIndeterminate(true);// 是否形成一个加载动画  true表示不明确加载进度形成转圈动画  false 表示明确加载进度
                progressDialog.setCancelable(false);//点击返回键或者dialog四周是否关闭dialog  true表示可以关闭 false表示不可关闭
                progressDialog.show();
                if(aBoolean){
                    progressDialog.setIcon(R.mipmap.ic_launcher);
                    progressDialog.setTitle("订单");
                    progressDialog.setMessage("发送成功");
                    progressDialog.setIndeterminate(false);// 是否形成一个加载动画  true表示不明确加载进度形成转圈动画  false 表示明确加载进度
                    progressDialog.setCancelable(true);//点击返回键或者dialog四周是否关闭dialog  true表示可以关闭 false表示不可关闭
                    progressDialog.show();
                    progressDialog.dismiss();
                    setResult(1);
                    finish();

                    return;
                }
                progressDialog.dismiss();
                progressDialog.setIcon(R.mipmap.ic_launcher);
                progressDialog.setTitle("订单");
                progressDialog.setMessage("发送失败");
                progressDialog.setIndeterminate(false);// 是否形成一个加载动画  true表示不明确加载进度形成转圈动画  false 表示明确加载进度
                progressDialog.setCancelable(true);//点击返回键或者dialog四周是否关闭dialog  true表示可以关闭 false表示不可关闭
                progressDialog.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        progressDialog.dismiss();
                        t.cancel();
                    }
                }, 3000);

            }
        });
    }

    private void initData(){
        //创建数据源
        //创建一个ViewModel的工厂
        ViewModelProvider.Factory factory = ViewModelProvider.
                AndroidViewModelFactory.getInstance(getApplication());
        //创建ViewModel的管理对象
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        //生产ViewModel
        routePlanActivityViewModel = viewModelProvider.
                get(RoutePlanActivityViewModel.class);

        routePlanActivityViewModel.loadingData();

        // 设置初始中心点搭车点
        LatLng center = routePlanActivityViewModel.getPoiMutableLiveData().getValue().getLatLng();
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(center, 18);
        baiduMap.setMapStatus(mapStatusUpdate);

    }

    private void initView(){
        setTitle("路线规划");
        baiduMap = activityRoutePlanBinding.mapviewRouteplan.getMap();
        baiduMap.setTrafficEnabled(true);
        mSearch = RoutePlanSearch.newInstance();
        passengerDialog = new PassengerDialog(this);



    }

    private void initListener(){

        listener = new OnGetRoutePlanResultListener() {

            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
                //创建DrivingRouteOverlay实例
                DrivingRouteOverlay overlay = new DrivingRouteOverlay(baiduMap);


                if(null !=drivingRouteResult) {
                    Log.d(TAG,drivingRouteResult.getRouteLines().get(0).getStarting().getLocation().toString());
                    Log.d(TAG,drivingRouteResult.getRouteLines().get(0).getTerminal().getLocation().toString());
                    Log.d(TAG,drivingRouteResult.getRouteLines().get(0).getCongestionDistance()+"");
                    Log.d(TAG,drivingRouteResult.getRouteLines().get(0).getDistance()+"");
                    Log.d(TAG,drivingRouteResult.getRouteLines().get(0).getDuration()+"");

                    routePlanActivityViewModel.loadingRoute(drivingRouteResult.getRouteLines().get(0));

                    if (drivingRouteResult.getRouteLines().size() > 0) {
                        //获取路径规划数据,(以返回的第一条路线为例）
                        //为DrivingRouteOverlay实例设置数据
                        overlay.setData(drivingRouteResult.getRouteLines().get(0));
                        //在地图上绘制DrivingRouteOverlay
                        overlay.addToMap();

                        //设置缩放级别
                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        builder.include(
                                drivingRouteResult.getRouteLines().get(0).getStarting().getLocation());
                        builder.include(
                                drivingRouteResult.getRouteLines().get(0).getTerminal().getLocation());

                        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngBounds(builder.build());
                        baiduMap.setMapStatus(mapStatusUpdate);
                        MapStatusUpdate msu = MapStatusUpdateFactory.zoomBy(-0.8f);
                        baiduMap.setMapStatus(msu);
                    }
                }
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        };

        //
        activityRoutePlanBinding.tvPassengersetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                passengerDialog.show();
            }
        });

        passengerDialog.getBtn_cancel().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passengerDialog.dismiss();
            }
        });

        passengerDialog.getBtn_confirm().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activityRoutePlanBinding.tvPassengersetting.setText("乘客："
                    +passengerDialog.getPassengerNumberPicker().getValue());
                passengerDialog.dismiss();

            }
        });



        activityRoutePlanBinding.btnSendorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routePlanActivityViewModel.sendingOrder(
                        apiService,v.getContext(),
                        passengerDialog.getPassengerNumberPicker().getValue());
            }
        });

    }



    private void startRoutePlan(){

        //分别设置起点、终点文本提示框
        addMarKerToMap(
                routePlanActivityViewModel.getPoiMutableLiveData().getValue().getPoiName(),
                routePlanActivityViewModel.getPoiMutableLiveData().getValue().getLatLng());
        addMarKerToMap(
                routePlanActivityViewModel.getEndPoiMutableLiveData().getValue().getPoiName(),
                routePlanActivityViewModel.getEndPoiMutableLiveData().getValue().getLatLng());

        mSearch.setOnGetRoutePlanResultListener(listener);

        PlanNode snode = PlanNode.withLocation(
                routePlanActivityViewModel.getPoiMutableLiveData().getValue().getLatLng());
        PlanNode enode = PlanNode.withLocation(
                routePlanActivityViewModel.getEndPoiMutableLiveData().getValue().getLatLng());
//        PlanNode stNode = PlanNode.withCityNameAndPlaceName(
//                routePlanActivityViewModel.getAddressMutableLiveData().getValue().getCity(),
//                routePlanActivityViewModel.getPoiMutableLiveData().getValue().getPoiName());
//        PlanNode enNode = PlanNode.withCityNameAndPlaceName(
//                routePlanActivityViewModel.getAddressMutableLiveData().getValue().getCity(),
//                routePlanActivityViewModel.getEndPoiMutableLiveData().getValue().getPoiName());

        Log.d(TAG,"起点："+snode.getCity()+" "+snode.getName()+" "+snode.getLocation());
        Log.d(TAG,"终点："+enode.getCity()+" "+enode.getName()+" "+enode.getLocation());

        mSearch.drivingSearch((new DrivingRoutePlanOption())
                .from(snode)
                .to(enode));


    }

    /**
     * 设置地图文本提示框
     * @param poiName
     * @param latLng
     */
    private void addMarKerToMap(String poiName,LatLng latLng){

        TextView textView = new TextView(this);
        textView.setText(poiName);
        textView.setBackgroundColor(Color.WHITE);
        InfoWindow infoWindow = new InfoWindow(
                textView, latLng, -47);
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(mBitmapDescriptor)
                .position(latLng)
                .scaleX(0.5f).scaleY(0.5f).infoWindow(infoWindow);
        baiduMap.addOverlay(markerOptions);
    }

    @Override
    protected void onResume() {
        activityRoutePlanBinding.mapviewRouteplan.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        activityRoutePlanBinding.mapviewRouteplan.onPause();
        if(null != progressDialog) {
            passengerDialog.dismiss();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        baiduMap.setMyLocationEnabled(false);
        activityRoutePlanBinding.mapviewRouteplan.onDestroy();
        mSearch.destroy();
        if(null != progressDialog) {
            passengerDialog.dismiss();
        }
        super.onDestroy();
    }

    @Override
    protected void onStop()
    {
        // 关闭图层定位
        baiduMap.setMyLocationEnabled(false);
        super.onStop();
    }
}
